import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/view/home/wifi/view_client.dart';
import 'package:flutter_chip/view/home/wifi/view_server.dart';
import 'package:wakelock/wakelock.dart';

class WifiPage extends StatefulWidget {
  @override
  _WifiPageState createState() => _WifiPageState();
}

class _WifiPageState extends State<WifiPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  String status = '';

  @override
  void initState() {
    super.initState();
    Wakelock.enable();
    _tabController = TabController(length: 2, initialIndex: 0, vsync: this);
    initWifi();
  }

  StreamSubscription subscription;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          elevation: 1,
          backgroundColor: Theme.of(context).canvasColor,
          titleSpacing: 0,
          title: Column(
            children: <Widget>[
              Text(
                '网络助手',
                style: TextStyle(fontSize: 18),
              ),
              Text('$status', style: TextStyle(fontSize: 12)),
            ],
          ),
          centerTitle: true,
          bottom: TabBar(
            controller: _tabController,
            indicator: BoxDecoration(),
            unselectedLabelColor: Color(0xff333333),
            labelColor: Theme.of(context).accentColor,
            labelStyle: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
            tabs: <Widget>[
              Text('客户端'),
              Text('服务器'),
            ],
          ),
        ),
        preferredSize: Size.fromHeight(Comm.screenHeight * 0.14),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ClientPage(),
          ServerPage(),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    subscription.cancel();
    Wakelock.disable();
  }

  ///初始化网络监听
  void initWifi() async {
    var connectivity = Connectivity();
    var check = await connectivity.checkConnectivity();
    String wifiName;
    if (check == ConnectivityResult.wifi) {
      wifiName = await connectivity.getWifiName();
      if (null == wifiName) {
        status = 'WIFI已连接';
      } else {
        status = "已连接：$wifiName";
      }
    } else {
      status = "请先连接一个WIFI";
    }
    setState(() {});
    subscription = connectivity.onConnectivityChanged
        .listen((ConnectivityResult result) async {
      if (result == ConnectivityResult.wifi) {
        wifiName = await connectivity.getWifiName();
        if (null == wifiName) {
          status = 'WIFI已连接';
        } else {
          status = "已连接：$wifiName";
        }
      } else {
        status = "请先连接一个WIFI";
      }
      setState(() {});
    });
  }
}
